<template>
    <div class="reward-exchange">
        <h1>兑换奖品</h1>
        <h2>可兑换奖品</h2>
        <ul class="item-list">
            <li v-for="item in items" :key="item.id" class="item">
                <h3>{{ item.name }}</h3>
                <p>所需积分: {{ item.cost }}</p>
                <p>库存: {{ item.store }}</p>
                <button :disabled="item.cost > userScore || item.store <= 0" @click="exchangeItem(item.id)">
                    兑换
                </button>
            </li>
        </ul>
        <button @click="goBack">返回</button>
    </div>
</template>

<script setup>

import service from "@/axios";
import useItem from "@/hooks/useItem";
import { onMounted, computed } from "vue";

const { items, getAllItems } = useItem();

const exchangeItem = async (itemId) => {
    try {
        console.log(1, JSON.parse(localStorage.getItem("loginUser")));
        const userId = JSON.parse(localStorage.getItem("loginUser")).id;
        const response = await service.post(`/buyItem?userId=${userId}&itemId=${itemId}`);
        alert("兑换成功")
        console.log(2, response.data.data.data);
        localStorage.setItem("loginUser", JSON.stringify(response.data.data.data));
        await getAllItems();
    } catch (error) {
        console.error('兑换失败', error);
    }
};

function goBack() {
    window.history.back();
}

onMounted(async () => {
    await getAllItems();
})

const userScore = computed(() => {
    return JSON.parse(localStorage.getItem("loginUser")).score;
})

</script>

<style scoped>
h1 {
    text-align: center;
    color: #333;
}

.reward-exchange {
    padding: 20px;
    max-width: 600px;
    margin: 0 auto;
    border: 1px solid #ddd;
    border-radius: 8px;
    background-color: #f4f4f9;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.item-list {
    list-style-type: none;
    padding: 0;
}

.item {
    border: 1px solid #ccc;
    padding: 15px;
    margin-bottom: 10px;
    background-color: #fff;
}

button {
    background-color: #28a745;
    color: white;
    border: none;
    padding: 10px 15px;
    cursor: pointer;
    border-radius: 5px;
}

button:disabled {
    background-color: #ccc;
    cursor: not-allowed;
}
</style>